# -*- coding: utf-8 -*-
# @Author	: changfeng
# @Date		: 2025/9/13 17:06
# @Last Modified by:   changfeng
# @Last Modified time: 2025/9/13 17:06
# Thanks for your comments!
import time
from typing import Optional, List

from bson import ObjectId
from pymongo import UpdateOne
from src.basedata.domain.po import AppAdministrationMappingPO
from src.basedata.domain.repositories import AppAdministrationMappingAbstractRepository
from src.basedata.infrastructure.client.mongodb.repository import MongoDBRepository
from src.basedata.infrastructure.utils import const


class MotorAppAdministrationMappingRepository(AppAdministrationMappingAbstractRepository, MongoDBRepository):
    def __init__(self, session):
        MongoDBRepository.__init__(self, session, const.AppAdministrationMapping)

    async def batch_save(self, data: List[AppAdministrationMappingPO]):
        bulk_ops = []
        for po in data:
            # 条件：匹配 code
            filter_query = {"app_adm": po.app_adm, "app_id": po.app_id, 'obsoleted': False}
            # 操作：存在则更新（$set 覆盖字段），不存在则新增
            update_value = po.dict(exclude_none=True)
            created_at = update_value.pop("created_at", None) or (time.time() * 1000)
            created_by = update_value.pop("created_by", None)
            obsoleted = update_value.pop("obsoleted", False)

            update_query = {
                "$set": update_value,
                "$setOnInsert": {"created_at": created_at, "created_by": created_by, "obsolete": obsoleted},
            }
            # 添加 upsert 操作
            bulk_ops.append(UpdateOne(filter_query, update_query, upsert=True))
        if bulk_ops:
            await self.bulk_write(bulk_ops, ordered=False)
